package com.business.dashboard.controller;

import com.business.dashboard.entity.BusinessPlan;
import com.business.dashboard.service.BusinessPlanService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 管理员商业计划书管理控制器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/business-plans")
@Validated
public class AdminBusinessPlanController {

    @Autowired
    private BusinessPlanService businessPlanService;

    /**
     * 获取所有商业计划书
     */
    @GetMapping("")
    public ResultUtil<List<BusinessPlan>> getAllBusinessPlans() {
        try {
            List<BusinessPlan> plans = businessPlanService.getAllBusinessPlans();
            return ResultUtil.success("获取商业计划书列表成功", plans);
        } catch (Exception e) {
            log.error("获取商业计划书列表失败", e);
            return ResultUtil.error("获取商业计划书列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取商业计划书
     */
    @GetMapping("/{id}")
    public ResultUtil<BusinessPlan> getBusinessPlanById(
                                                       @PathVariable @NotNull Long id) {
        try {
            BusinessPlan plan = businessPlanService.getBusinessPlanById(id);
            if (plan != null) {
                return ResultUtil.success("获取商业计划书详情成功", plan);
            } else {
                return ResultUtil.error(404, "商业计划书不存在");
            }
        } catch (Exception e) {
            log.error("获取商业计划书详情失败，planId: {}", id, e);
            return ResultUtil.error("获取商业计划书详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建商业计划书
     */
    @PostMapping("")
    public ResultUtil<BusinessPlan> createBusinessPlan(
                                                      @RequestBody @Valid BusinessPlan plan) {
        try {
            BusinessPlan createdPlan = businessPlanService.createBusinessPlan(plan);
            return ResultUtil.success("创建商业计划书成功", createdPlan);
        } catch (Exception e) {
            log.error("创建商业计划书失败，", e);
            return ResultUtil.error("创建商业计划书失败：" + e.getMessage());
        }
    }

    /**
     * 创建商业计划书模板
     */
    @PostMapping("/templates")
    public ResultUtil<BusinessPlan> createBusinessPlanTemplate(
                                                             @RequestBody @Valid BusinessPlan plan) {
        try {
            // 管理员创建的计划书作为模板
            plan.setStatus("template");
            // 设置系统用户ID为模板创建者，使用ID为0表示系统模板
            if (plan.getUserId() == null) {
                plan.setUserId(0L);
            }
            BusinessPlan createdPlan = businessPlanService.createBusinessPlan(plan);
            return ResultUtil.success("创建商业计划书模板成功", createdPlan);
        } catch (Exception e) {
            log.error("创建商业计划书模板失败，", e);
            return ResultUtil.error("创建商业计划书模板失败：" + e.getMessage());
        }
    }

    /**
     * 更新商业计划书
     */
    @PutMapping("/{id}")
    public ResultUtil<BusinessPlan> updateBusinessPlan(
                                                      @PathVariable @NotNull Long id,
                                                      @RequestBody @Valid BusinessPlan plan) {
        try {
            plan.setId(id);
            BusinessPlan updatedPlan = businessPlanService.updateBusinessPlan(plan);
            return ResultUtil.success("更新商业计划书成功", updatedPlan);
        } catch (Exception e) {
            log.error("更新商业计划书失败，planId: {}", id, e);
            return ResultUtil.error("更新商业计划书失败：" + e.getMessage());
        }
    }

    /**
     * 删除商业计划书
     */
    @DeleteMapping("/{id}")
    public ResultUtil<String> deleteBusinessPlan(
                                                @PathVariable @NotNull Long id) {
        try {
            boolean deleted = businessPlanService.deleteBusinessPlan(id);
            if (deleted) {
                return ResultUtil.success("删除商业计划书成功");
            } else {
                return ResultUtil.error("删除商业计划书失败");
            }
        } catch (Exception e) {
            log.error("删除商业计划书失败，planId: {}", id, e);
            return ResultUtil.error("删除商业计划书失败：" + e.getMessage());
        }
    }

    /**
     * 审核商业计划书
     */
    @PutMapping("/{id}/review")
    public ResultUtil<String> reviewBusinessPlan(
                                                @PathVariable @NotNull Long id,
                                                @RequestParam String status,
                                                @RequestParam(required = false) String comment) {
        try {
            boolean reviewed = businessPlanService.reviewBusinessPlan(id, status, comment, 1L);
            if (reviewed) {
                return ResultUtil.success("审核商业计划书成功");
            } else {
                return ResultUtil.error("审核商业计划书失败");
            }
        } catch (Exception e) {
            log.error("审核商业计划书失败，planId: {}", id, e);
            return ResultUtil.error("审核商业计划书失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新商业计划书状态
     */
    @PutMapping("/batch/status")
    public ResultUtil<String> batchUpdateStatus(
                                               @RequestParam List<Long> ids,
                                               @RequestParam String status) {
        try {
            boolean updated = businessPlanService.batchUpdateStatus(ids, status);
            if (updated) {
                return ResultUtil.success("批量更新状态成功");
            } else {
                return ResultUtil.error("批量更新状态失败");
            }
        } catch (Exception e) {
            log.error("批量更新商业计划书状态失败，", e);
            return ResultUtil.error("批量更新状态失败：" + e.getMessage());
        }
    }

    /**
     * 导出商业计划书为PDF
     */
    @GetMapping("/{id}/export/pdf")
    public ResultUtil<Object> exportToPdf(
                                         @PathVariable @NotNull Long id) {
        try {
            // TODO: 实现PDF导出功能
            String downloadUrl = businessPlanService.exportToPdf(id);
            return ResultUtil.success("导出PDF成功", downloadUrl);
        } catch (Exception e) {
            log.error("导出商业计划书PDF失败，planId: {}", id, e);
            return ResultUtil.error("导出PDF失败：" + e.getMessage());
        }
    }

    /**
     * 获取商业计划书统计数据
     */
    @GetMapping("/stats")
    public ResultUtil<Object> getBusinessPlanStats() {
        try {
            Object stats = businessPlanService.getBusinessPlanStats();
            return ResultUtil.success("获取商业计划书统计成功", stats);
        } catch (Exception e) {
            log.error("获取商业计划书统计失败，", e);
            return ResultUtil.error("获取商业计划书统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门行业分析
     */
    @GetMapping("/industries/trending")
    public ResultUtil<Object> getTrendingIndustries() {
        try {
            Object trending = businessPlanService.getTrendingIndustries();
            return ResultUtil.success("获取热门行业成功", trending);
        } catch (Exception e) {
            log.error("获取热门行业失败，", e);
            return ResultUtil.error("获取热门行业失败：" + e.getMessage());
        }
    }
}